package 堆排序;

import java.util.Arrays;

public class heapSort {

    public static void swap(int[] array,int i,int j) {
        int tmp=array[i];
        array[i]=array[j];
        array[j]=tmp;
    }

    public static void createHeap(int[] array) {
        for(int parent=(array.length-1-1)/2;parent>=0;parent--){
            shiftDown(array,parent,array.length);
        }
    }
    public static void shiftDown(int[] array,int parent,int len){
        int child=2*parent+1;
        while(child<len ){
            if(child+1<len && array[child]<array[child+1]){
                child++;
            }
            if(array[child]>array[parent]){
                swap(array,child,parent);
                parent=child;
                child=2*parent+1;
            }else{
                break;
            }
        }

    }
    public static void heapsort(int[] array){
        //建堆  O(n)
        createHeap(array);
        int end=array.length-1;
        //交换调整O(n * log n)
        while(end > 0){
            swap(array,0,end);
            shiftDown(array,0,end);
            end--;
        }
    }

    public static void main(String[] args) {
        int[] array={12,5,9,34,0,33,6,55};
        heapsort(array);
        System.out.println(Arrays.toString(array));
    }


}
